#include "FadeTips.h"

#include <core/StyleMgr.h>

#include <QFontMetrics>
#include <QStylePainter>
#include <QTimer>

FadeTips::FadeTips(QWidget* p)
    : QWidget(p, Qt::FramelessWindowHint | Qt::Tool) {
  setAttribute(Qt::WA_TranslucentBackground);
  m_timer = new QTimer(this);
  m_timer->callOnTimeout(this, &FadeTips::onTimer);

  QFont f = font();
  f.setBold(true);
  f.setPixelSize(15);
  setFont(f);
}

void FadeTips::setMargin(int x, int y) {
  m_hMargin = x;
  m_vMargin = y;
}

QSize FadeTips::sizeHint() const {
  if (sizePolicy().horizontalPolicy() == QSizePolicy::Fixed ||
      sizePolicy().verticalPolicy() == QSizePolicy::Fixed)
    return QWidget::sizeHint();

  QFontMetrics metrics(font());
  QRect txtR = metrics.boundingRect(m_msg);
  return {txtR.width() + m_hMargin * 2, txtR.height() + m_vMargin * 2};
}

void FadeTips::mousePressEvent(QMouseEvent* event) { hideMe(); }

void FadeTips::paintEvent(QPaintEvent* event) {
  QStylePainter painter(this);
  QColor bkColor = StyleMgr::instance().color("BackNormal");
  bkColor.setAlpha((10 - m_count) / 10.0 * 255);
  painter.setBrush(bkColor);
  QColor penColor = StyleMgr::instance().color("Up_Increase_H1");
  penColor.setAlpha((10 - m_count) / 10.0 * 255);
  QPen pen(penColor);
  pen.setWidth(2);
  painter.setPen(pen);

  QRect r = rect();
  r.adjust(1, 1, -1, -1);
  painter.drawRoundedRect(r, 2, 2);
  painter.drawText(r, m_msg, QTextOption(Qt::AlignCenter));
}

void FadeTips::showEvent(QShowEvent* event) {
  QWidget::showEvent(event);
  m_timer->start(3000);
}

void FadeTips::onTimer() {
  if (!m_hiding) {
    m_hiding = true;
    m_timer->stop();
    m_timer->start(100);
  } else {
    ++m_count;
    update();
    if (m_count == 10) {
      hideMe();
    }
  }
}

void FadeTips::hideMe() {
  m_hiding = false;
  m_timer->stop();
  m_count = 0;
  hide();
}
